/*
 * @Author: weidewei
 * @Date: 2025-11-01 11:29:22
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-01 12:00:12
 * @Description: 
 * @FilePath: \2025-front-face\js常见手写题\myCall.js
 */


function test(name,age) {
    // console.log(this);
    this.name = name;
    this.age = age;
}

const p = {};
// test.call(888,'正三',18); // this:888
// test.call(null,'正三',18); // this:globalThis
// test.call(undefined,'正三',18); // this:globalThis
// test.call(p,'正三',18); // this:p


/*
1.this指向确认：null或者undefined指向全局，否则指向传入的this的包装对象
2.避免属性冲突​
3.临时绑定 this
4.调用函数并传参​
5.清理临时属性​
6.返回结果​
*/
Function.prototype.myCall = function (ctx,...args) {
    // ctx要用包装对象
    ctx = (ctx === null || ctx === undefined) ? globalThis : Object(ctx);
    // console.log(ctx,...args)
    const fnKey = Symbol('key');
    Object.defineProperty(ctx,fnKey,{
        value: this
    });
    const result = ctx[fnKey](...args);
    delete ctx[fnKey];
    return result;
    
}

test.myCall(null,1,2);
